/**
 * Created by DevilsEyes on 2016/3/14.
 */
define(['text!path/productList/tmp.html?' + cacheControl, 'timer', 'iscroll', 'layer'], function (page, timer, is, layer) {
    'use strict';
    var symbol = {};//标记位

    var subtemplate = {};//子模版
    //通过division标识把可复用的部分模版提取出来
    page = page.replace(/\{\{division "(.+?)"}}([\s\S]+?)\{\{\/division}}/g, function (origin, id, tmp, index) {
        subtemplate[id] = template.compile(tmp);
        return tmp;
    });
    var render = template.compile(page);//主模版

    //获取请求
    var Query = function (queryStr) {
        var that = this;
        queryStr.replace(/([^=&]*)(?:=)?([^=&]*)?/g, function (str, key, value, index) {
            if (str != '') {
                that[key] = value;
            }
            return str;
        });
    };
    var Brand = {
        selected: '',
        map: {},
        scroller: null,
        list: [],
        isShow: false,
        promise: null,
        init: function (categoryId) {
            this.promise = new Promise(function (resolve) {
                Brand.map = {};
                Brand.isShow = false;
                Brand.list = [];
                ex.jsonp({
                    url: api + 'commodity/list/brand',
                    data: {
                        category_id: categoryId
                    },
                    success: function (obj) {
                        if (obj.code == 0) {

                            var data = obj.data || [];
                            data.forEach(function (v) {
                                Brand.map[v._id] = v;
                                Brand.list.push(v);
                            });
                            resolve();

                        } else {
                            layer.msg(obj.msg);
                        }
                    }
                })
            })
        },
        ready: function () {
            this.promise && this.promise.done(function () {
                var $brand = vm.$.brandArea;
                Brand.scroller && Brand.scroller.destroy();
                $brand.html(subtemplate.brand({
                    brandList: Brand.list
                }));
                //只有显示的DOM才会被渲染，才能使用iScroll
                $brand.show();
                ex.async(function () {

                    vm.bindEvent(vm.event, $brand);
                    vm.bind$(vm.$, $brand);
                    Brand.set(Brand.selected);
                    Brand.scroller = new IScroll('.brandArea', {
                        tap: true,
                        scrollX: true,
                        scrollY: false
                    });
                    $brand.hide();
                })
            });
        },
        show: function () {
            if (this.isShow)return;
            var $brand = vm.$.brandArea;
            timer
                .queue(function () {
                    $brand.show();
                    $brand.height(0);
                })
                .go(function () {
                    $brand.height(116 + 28);
                })
                .go(function () {
                    symbol.inAnime = false;
                    Brand.isShow = true;
                }, 300)
        },
        hide: function () {
            if (!this.isShow)return;
            var $brand = vm.$.brandArea;
            timer
                .queue(function () {
                    $brand.height(0);
                })
                .go(function () {
                    $brand.hide();
                    symbol.inAnime = false;
                    Brand.isShow = false;
                }, 300)
        },
        set: function (id) {
            if (id) {
                this.selected = id;
                vm.$.brandTab.addClass('active').find('span').text(this.map[id].name);
            } else {
                this.selected = '';
                vm.$.brandTab.removeClass('active').find('span').text('品牌');
            }
        }
    };
    var Category = {
        selected: '',
        map: {},
        list: [],
        mainId: '',
        mainScroller: null,
        subScroller: null,
        isShow: false,
        promise: null,
        init: function () {
            this.promise = new Promise(function (resolve) {
                Category.map = {};
                Category.list = [];
                Category.mainId = '';
                ex.jsonp({
                    url: api + 'commodity/list/category',
                    success: function (obj) {
                        if (obj.code == 0) {

                            var data = obj.data;
                            data.forEach(function (v) {
                                Category.map[v._id] = v;
                                Category.list.push(v);
                            });
                            resolve();
                        }
                    }
                })
            })
        },
        ready: function () {
            this.promise && this.promise.done(function () {
                Category.reRender(Category.getMainId());
                Category.set(Category.selected);
            });
        },
        getMainId: function () {
            return this.list.filter(function (v, i) {
                if (v._id == Category.selected)return true;
                for (var i = 0; i < v.children.length; i++) {
                    if (v.children[i]._id == Category.selected) {
                        return true;
                    }
                }
                return false;
            })[0]._id
        },
        reRender: function (mainId) {
            if (this.mainId == mainId)return;
            this.mainId = mainId;
            var $category = vm.$.categoryArea;
            var index = Category.list.indexOf(Category.map[mainId]);

            this.mainScroller && this.mainScroller.destroy();
            this.subScroller && this.subScroller.destroy();

            $category.html(subtemplate.category({
                categoryList: Category.list,
                categorySubList: Category.map[mainId].children
            }));

            //只有显示的DOM才会被渲染，才能使用iScroll
            $category.show();
            ex.async(function () {

                vm.bindEvent(vm.event, $category);
                vm.bind$(vm.$, $category);

                Category.mainScroller = new IScroll('.mainlist', {
                    tap: true,
                    scrollX: false,
                    scrollY: true
                });
                Category.subScroller = new IScroll('.sublist', {
                    tap: true,
                    scrollX: false,
                    scrollY: true
                });
                $('.mainlist li').removeClass('select');

                vm.$['categoryMainList' + index].addClass('select');
                if (!Category.isShow)$category.hide();
            })
        },
        show: function () {
            if (this.isShow)return;
            var $category = vm.$.categoryArea;
            timer
                .queue(function () {
                    $category.show();
                    $category.height(0);
                })
                .go(function () {
                    $category.height(200);
                })
                .go(function () {
                    symbol.inAnime = false;
                    Category.isShow = true;
                }, 300)
        },
        hide: function () {
            if (!this.isShow)return;
            var $category = vm.$.categoryArea;
            timer
                .queue(function () {
                    $category.height(0);
                })
                .go(function () {
                    $category.hide();
                    symbol.inAnime = false;
                    Category.isShow = false;
                }, 300)
        },
        set: function (id) {
            this.selected = id;
            vm.$.categoryTab
                .addClass('active')
                .find('span')
                .text(
                    //获取该分类的名称
                    this.list.reduce(function (last, now) {
                        if (now._id == id)return last.concat([now.name]);
                        for (var i = 0; i < now.children.length; i++) {
                            if (now.children[i]._id == id) {
                                return last.concat([now.children[i].name]);
                            }
                        }
                        return last.concat([]);
                    }, [])[0]
                );
        }
    };
    var Shade = {
        isShow: false,
        show: function (zIndex) {
            //设置z-index
            var $shade = vm.$.shade;
            $shade.css({
                "z-index": zIndex
            });
            if (this.isShow == true)return;
            //闭合->展开
            timer
                .queue(function () {
                    $shade.show();
                    $shade.css({
                        opacity: 0
                    });
                })
                .go(function () {
                    $shade.css({opacity: 1});
                })
                .go(function () {
                    Shade.isShow = true;
                }, 300)
        },
        hide: function () {
            if (this.isShow == false)return;
            //展开->闭合
            var $shade = vm.$.shade;
            timer
                .queue(function () {
                    $shade.css({
                        opacity: 0
                    });
                })
                .go(function () {
                    $shade.hide();
                    Shade.isShow = false;
                }, 300)
        }
    };
    var Filter = {
        isShow: false,
        promise: null,
        SpecList: [],
        selected: {},
        scroller: null,
        init: function (options) {
            this.promise = new Promise(function (resolve) {
                Filter.map = {};
                Filter.isShow = false;
                Filter.list = [];
                ex.jsonp({
                    url: api + 'commodity/list/specs',
                    data: function () {
                        var data = {};
                        if (options.spu_id) {
                            data.spu_id = options.spu_id;
                        } else {
                            if (options.category_id)data.category_id = options.category_id;
                            if (options.brand_id)data.brand_id = options.brand_id;
                        }
                        return data;
                    }(),
                    success: function (obj) {
                        if (obj.code == 0) {

                            var data = obj.data || [];
                            Filter.SpecList = data.relative.map(function (v) {
                                return data.specs.reduce(function (last, now) {
                                    if (now.spec_id == v.key) {
                                        return $.extend(now, {select: ""});
                                    } else {
                                        return last;
                                    }
                                }, null);
                            });
                            data.strategylist && data.strategylist.forEach(function (v) {
                                Filter.SpecList.forEach(function (specs) {
                                    if (specs.spec_id == v.spec_id) {
                                        specs.strategy = true;
                                        specs.depart = '';
                                        specs.select = '';
                                        specs.strategyList = v.list;
                                    }
                                }, null);
                            });

                            for (var key in Filter.selected) {
                                if (Filter.selected[key]) {

                                    Filter.SpecList.forEach(function (specs) {
                                        if (specs.spec_id == key) {
                                            specs.select = Filter.selected[key];
                                            if (specs.strategy) {
                                                for (var t in specs.strategyList) {
                                                    if (t[key]) {
                                                        specs.depart = t;
                                                    }
                                                }
                                            }
                                        }
                                    }, null);

                                }
                            }
                            resolve();
                        } else {
                            layer.msg(obj.msg);
                        }
                    }
                })
            })
        },
        ready: function () {
            this.promise && this.promise.done(function () {
                Filter.reload();
            });
        },
        reload: function () {
            var $filter = vm.$.filterArea;
            Filter.scroller && Filter.scroller.destroy();
            $filter.html(subtemplate.filter({
                filterList: Filter.SpecList
            }));
            //只有显示的DOM才会被渲染，才能使用iScroll
            $filter.show();
            ex.async(function () {

                vm.bindEvent(vm.event, $filter);
                vm.bind$(vm.$, $filter);

                Filter.SpecList.forEach(function (S) {
                    if (S.strategy && S.depart) {
                        $("[data-strategy='" + S.spec_id + ">" + S.depart + "']").addClass('select');
                    }
                    if (S.select) {
                        $("[data-tag='" + S.spec_id + ">" + S.select + "']").addClass('select');
                    }
                });

                Filter.scroller = new IScroll('.filter-list', {
                    tap: true,
                    scrollX: false,
                    scrollY: true
                });
                if (!Filter.isShow)$filter.hide();
            })
        },
        expand: function (id, value) {
            Filter.SpecList.forEach(function (S) {
                if (S.strategy && S.spec_id == id) {
                    S.depart = value;
                    S.select = '';
                    Filter.selected[id] = '';
                }
            });
            Filter.reload();
        },
        set: function (id, value) {
            Filter.SpecList.forEach(function (S) {
                if (S.spec_id == id) {
                    S.select = value;
                    Filter.selected[id] = value;
                }
            });
            Filter.reload();
        },
        show: function () {
            if (this.isShow)return;
            var $filter = vm.$.filterArea;
            var $footer = vm.$.footer;
            timer
                .queue(function () {
                    $filter.show();
                    $footer.show();
                    $filter.css({
                        right: '-90%'
                    });
                    $footer.css({
                        bottom: -44
                    });
                })
                .go(function () {
                    $filter.css({
                        right: 0
                    });
                    $footer.css({
                        bottom: 0
                    });
                })
                .go(function () {
                    symbol.inAnime = false;
                    Filter.isShow = true;
                }, 300)
        },
        hide: function () {
            if (!this.isShow)return;
            var $filter = vm.$.filterArea;
            var $footer = vm.$.footer;
            timer
                .queue(function () {
                    $filter.css({
                        right: '-90%'
                    });
                    $footer.css({
                        bottom: -44
                    });
                })
                .go(function () {
                    $filter.hide();
                    $footer.hide();
                    symbol.inAnime = false;
                    Filter.isShow = false;
                }, 300)
        },
        clear: function () {
            Filter.selected = {};
            Filter.SpecList.forEach(function (S) {
                if (S.strategy && S.depart) {
                    S.depart = '';
                }
                S.select = '';
            });
            Filter.reload();
        }
    };
    var Cache = {
        query: {},
        getAndClear: function () {
            var data = db.get('productListCache');
            db.clear('productListCache');
            Cache.query = {};
            if (data && (JSON.stringify(vm.query) == JSON.stringify(data.query))) {
                if (data.spu) {
                    vm.sputitle = data.sputitle;
                } else {
                    Category.selected = data.category;
                    Brand.selected = data.brand;
                }
                Filter.selected = data.filter;
                Cache.query = getPostData({
                    index: 0,
                    limit: data.length
                });
                return true;
            } else {
                return false;
            }
        },
        set: function () {
            var data = {
                query: vm.query,
                length: vm.data.list.length,
                spu: vm.query.spu || '',
                sputitle: vm.query.sputitle || '',
                brand: Brand.selected,
                category: Category.selected,
                filter: Filter.selected
            };
            console.log(data);
            db.set('productListCache', data);
        }
    };

    var getPostData = function (options) {
        var QUERY = {};
        options = options || {};
        if (isNaN(options.index)) {
            QUERY.index = vm.data.list.length;
        } else {
            QUERY.index = options.index;
        }
        QUERY.limit = options.limit || vm.limit;
        if (vm.query.spu) {
            //查询SPU所属SKU模式
            QUERY.spu_id = vm.query.spu;
        } else {
            //标准模式
            QUERY.category_id = Category.selected;
            if (Brand.selected) {
                QUERY.brand_id = Brand.selected;
            }
        }
        //规格过滤
        QUERY.specs = [];
        for (var key in Filter.selected) {
            if (Filter.selected[key]) {
                QUERY.specs.push({
                    spec_id: key,
                    specvalue_id: Filter.selected[key]
                })
            } else {
                delete Filter.selected[key];
            }

        }
        return QUERY;
    };

    var vm = new Page.creat({
        $id: 'productList',
        $model: {
            data: {},
            $: {},
            limit: 5,
            timer: null,
            query: {},
            init: function (query) {
                //初始化
                symbol.isLoading = false;
                vm.timer && clearInterval(vm.timer);
                vm.query = new Query(query);
                var QUERY = {};

                if (vm.query.sputitle) {
                    vm.query.sputitle = decodeURIComponent(vm.query.sputitle);
                }


                //尝试解析Cache
                if (Cache.getAndClear()) {
                    QUERY = Cache.query;
                } else {
                    QUERY = {
                        index: 0,
                        limit: vm.limit
                    };
                    if (vm.query.spu) {
                        //查询SPU所属SKU模式
                        QUERY.spu_id = vm.query.spu;
                        Filter.init({
                            spu_id: QUERY.spu_id
                        })
                    } else {
                        //标准模式
                        if (vm.query.category) {
                            //必填
                            QUERY.category_id = vm.query.category;

                            Category.selected = vm.query.category;

                            Brand.init(vm.query.category);
                            Category.init();

                            if (vm.query.brand) {
                                QUERY.brand_id = vm.query.brand;
                                Brand.selected = vm.query.brand;
                            } else {
                                Brand.selected = '';
                            }

                            Filter.init({
                                category_id: Category.selected,
                                brand_id: Brand.selected
                            })
                        } else {
                            throw '分类和SPU至少拥有一项';
                        }
                    }
                }
                console.log(QUERY);
                symbol.isLoading = true;
                ex.jsonp({
                    url: api + 'commodity/list',
                    method: 'GET',
                    data: QUERY,
                    success: function (obj) {
                        if (!vm.isThisPage())return;

                        vm.data = {
                            list: obj.data.list || [],
                            spuTitle: vm.query.sputitle
                        };
                        $('#page').html(render(vm.data));


                        ex.async(function () {

                            vm.bindEvent(vm.event);
                            vm.bind$(vm.$);

                            $('.tag-timer').each(function () {
                                var $this = $(this);
                                var start = $this.attr('data-time');

                                var id = timer.register($this, function (time) {
                                    var t = start - (time - this.creatTime);

                                    if (t < 0) {
                                        timer.logout(id);
                                        this.$dom.find('span').html('已过期');
                                    } else {
                                        this.$dom.find('span').html(template.compile("{{t | formatTime:'hh:mm:ss'}}")({t: t}))
                                    }
                                })
                            });

                            Brand.ready();
                            Category.ready();
                            Filter.ready();
                            symbol.isLoading = false;
                            if (obj.data.count > obj.data.list.length) {
                                vm.timer = setInterval(vm.action.loadMore, 1000);
                                vm.$.tips.show().text('正在加载更多!');
                            } else if (obj.data.count == 0) {
                                vm.$.tips.show().text('一件商品也找不到哦!');
                            } else {
                                vm.$.tips.hide();
                            }
                            //回到之前保存的位置
                            vm.getLastPosition();
                        });
                    }
                })
            },
            event: {
                //开关品牌列表
                toggleBrandList: function () {
                    if (symbol.inAnime)return;
                    symbol.inAnime = true;
                    Category.hide();
                    if (Brand.isShow) {
                        Shade.hide();
                        Brand.hide();
                    } else {
                        Shade.show(10);
                        Brand.show();
                    }
                },
                //开关分类列表
                toggleCategoryList: function () {
                    if (symbol.inAnime)return;
                    symbol.inAnime = true;
                    Brand.hide();
                    if (Category.isShow) {
                        Shade.hide();
                        Category.hide();
                    } else {
                        Shade.show(10);
                        Category.show();
                    }
                },
                //点击阴影关闭
                shadeClose: function () {
                    Shade.hide();
                    Category.hide();
                    Brand.hide();
                    Filter.hide();
                },
                //开关筛选列表
                toggleFilterWindow: function () {
                    if (symbol.inAnime)return;
                    symbol.inAnime = true;
                    Category.hide();
                    Brand.hide();
                    if (Filter.isShow) {
                        Shade.hide();
                        Filter.hide();
                    } else {
                        Shade.show(20);
                        Filter.show();
                    }
                },
                //修改分类子表
                changeCategory: function (id) {
                    Category.reRender(id);
                },
                //修改分类值
                selectCategory: function (id) {
                    id = id || Category.mainId;
                    Category.set(id);
                    Category.hide();
                    Shade.hide();
                    Brand.set('');
                    Filter.clear();
                    vm.action.refreshList();
                },
                //修改品牌值
                selectBrand: function (id) {
                    id = id || Brand.mainId;
                    Brand.set(id);
                    Brand.hide();
                    Shade.hide();
                    Filter.clear();
                    vm.action.refreshList();
                },
                //展开某一规格
                expandFilter: function () {
                    var kv = $(this).attr('data-strategy');
                    kv = kv.split('>');
                    var k = kv[0];
                    var v = kv[1];
                    Filter.expand(k, v);
                },
                //选择规格值
                setFilter: function () {
                    var kv = $(this).attr('data-tag');
                    kv = kv.split('>');
                    var k = kv[0];
                    var v = kv[1];
                    Filter.set(k, v);
                },
                //清除所选规格
                clearFilter: function () {
                    Filter.clear();
                },
                //开始筛选
                Searching: function () {
                    vm.action.refreshList();
                    Shade.hide();
                    Filter.hide();
                },
                //浏览某件商品
                viewProduct: function (id) {
                    Cache.set();
                    location.hash = '#/productDetail/' + id;
                }
            },
            action: {
                //刷新列表
                refreshList: function () {

                    symbol.isLoading = true;
                    if(!vm.query.spu){
                        Brand.init(Category.selected);
                        Category.init();
                        Filter.init({
                            category_id: Category.selected,
                            brand_id: Brand.selected
                        });

                        Filter.init({
                            category_id: Category.selected,
                            brand_id: Brand.selected
                        })
                    }

                    ex.jsonp({
                        url: api + 'commodity/list',
                        method: 'GET',
                        data: getPostData({index: 0}),
                        success: function (obj) {
                            if (!vm.isThisPage())return;

                            vm.data = {
                                list: obj.data.list || [],
                                spuTitle: vm.query.sputitle
                            };
                            vm.$.productArea.html(subtemplate.product(vm.data));


                            ex.async(function () {

                                vm.bindEvent(vm.event, vm.$.productArea);
                                vm.bind$(vm.$, vm.$.productArea);

                                $('.tag-timer').each(function () {
                                    var $this = $(this);
                                    var start = $this.attr('data-time');

                                    var id = timer.register($this, function (time) {
                                        var t = start - (time - this.creatTime);
                                        if (t < 0) {
                                            timer.logout(id);
                                            this.$dom.find('span').html('已过期');
                                        } else {
                                            this.$dom.find('span').html(template.compile("{{t | formatTime:'hh:mm:ss'}}")({t: t}))
                                        }
                                    })
                                });

                                Brand.ready();
                                Category.ready();
                                Filter.ready();
                                symbol.isLoading = false;
                                if (obj.data.count > obj.data.list.length) {
                                    vm.timer && clearInterval(vm.timer);
                                    vm.timer = setInterval(vm.action.loadMore, 1000);
                                    vm.$.tips.show().text('正在加载更多!');
                                } else if (obj.data.count == 0) {
                                    vm.$.tips.show().text('一件商品也找不到哦!');
                                } else {
                                    vm.$.tips.hide();
                                }
                                //回到顶部
                                vm.getLastPosition(false);
                            });
                        }
                    })
                },
                loadMore: function () {
                    if (!vm.isThisPage())
                        return clearInterval(vm.timer);

                    if (symbol.isLoading)return;
                    console.log(vm.$.productArea.get(0).scrollHeight);
                    if (window.scrollY + db.h - vm.$.productArea.get(0).scrollHeight < -200)return;
                    symbol.isLoading = true;

                    ex.jsonp({
                        url: api + 'commodity/list',
                        method: 'GET',
                        data: getPostData(),
                        success: function (obj) {
                            symbol.isLoading = false;
                            if (!vm.isThisPage())return;

                            var Last = vm.data.list.length;

                            vm.data.list = vm.data.list.concat(obj.data.list);
                            vm.$.productArea.append(subtemplate.product({
                                list: obj.data.list
                            }));

                            if (vm.data.list.length == obj.data.count) {
                                clearInterval(vm.timer);
                                vm.$.tips.hide();
                            }

                            ex.async(function () {

                                $('.product').each(function (index) {
                                    if (index >= Last) {
                                        var $this = $(this);
                                        var $timer = $this.find('.tag-timer');

                                        vm.bindEvent(vm.event, $this);
                                        vm.bind$(vm.$, $this);

                                        if ($timer.length > 0) {
                                            var start = $timer.attr('data-time');

                                            var id = timer.register($timer, function (time) {
                                                var t = start - (time - this.creatTime);
                                                if (t < 0) {
                                                    timer.logout(id);
                                                    this.$dom.find('span').html('已过期');
                                                } else {
                                                    this.$dom.find('span').html(template.compile("{{t | formatTime:'hh:mm:ss'}}")({t: t}))
                                                }
                                            })
                                        }
                                    }
                                });

                            });
                        }
                    })
                }
            }
        }
    });


    return {
        init: function (params) {
            vm.$init({
                setTitle: '商品列表'
            });
            vm.init(params.query);
        }
    }
});